﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Common.Library.HTTP
{
    /// <summary>
    /// BasicAuth
    /// 一需要在请求头中添加Authorization: "Basic 用户名和密码的base64加密字符串"
    /// </summary>
    public static class HttpClientHelperBasicAuth
    {

        public static HttpResponseMessage Get(string url, string userName, string passWord, int timeOut = 60)
        {
            HttpResponseMessage response = null;
            using (var http = new HttpClient())
            {
                try
                {
                    http.Timeout = new TimeSpan(0, 0, timeOut);
                    var message = new HttpRequestMessage(HttpMethod.Get, url);
                    var authorization = BuildBase64String(userName, passWord);
                    message.Headers.Add("Authorization", authorization);
                    response = http.SendAsync(message).Result;
                    return response;
                }
                catch (Exception ex)
                {
                    response = new HttpResponseMessage(System.Net.HttpStatusCode.RequestTimeout) { Content = new StringContent("请求超时") };
                    return response;
                }
            }
        }



        /// <summary>
        /// 生成 BasicAuth  Authorization 参数
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        private static string BuildBase64String(string userName, string passWord)
        {
            string tempString = userName + ":" + passWord;
            string base64String = "Basic ";
            base64String += Convert.ToBase64String(new ASCIIEncoding().GetBytes(tempString));
            return base64String;
        }

    }
}
